package com.youbug.system.controller;


import com.youbug.common.vo.CommonTreeVo;
import com.youbug.common.vo.R;
import com.youbug.system.entity.Org;
import com.youbug.system.service.IOrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 机构表 前端控制器
 * </p>
 *
 * @author youbug
 * @since 2023-03-02
 */
@RestController
@RequestMapping("/org")
public class OrgController {

    @Autowired
    private IOrgService orgService;

    @GetMapping("/getOrgs")
    public R<List<Org>> getOrgs(){

        List<Org> orgs = orgService.getOrgs();

        return R.ok(orgs);
    }

    @GetMapping("/getParentOrgs")
    public R<List<CommonTreeVo>> getParentOrgs(){

        List<CommonTreeVo> treeVos = orgService.getParentOrgs();

        return R.ok(treeVos);
    }


    @GetMapping("/getOrg/{id}")
    public R<Org> getOrg(@PathVariable String  id){

        Org org = orgService.getById(id);

        return R.ok(org);
    }

    @PostMapping("/add")
    public R<Boolean> add(@RequestBody Org org){

        if(ObjectUtils.isEmpty(org.getPid())){
            org.setPid(0);
            org.setFullParentId("0|");
            org.setFullParentName("总公司|");
        }
        String[] split = org.getFullParentId().split("\\|");

        org.setLevel(split.length);

        boolean save = orgService.save(org);

        return  R.ok(save);
    }

    @GetMapping("/delete/{id}")
    public R<Boolean> add(@PathVariable String  id){

        boolean remove = orgService.deleteOrgById(id);

        return  remove? R.ok(remove): R.fail("该机构下存在用户不能删除");
    }

    @PostMapping("/update")
    public R<Boolean> update(@RequestBody Org org){

        boolean save = orgService.updateOrgById(org);

        return  R.ok(save);
    }
}

